package com.rongda.deploy.operation.deploy.controller.body;

import com.rongda.deploy.operation.deploy.dto.R;
import com.rongda.deploy.operation.deploy.pojo.App;
import com.rongda.deploy.operation.deploy.service.DAppService;
import com.rongda.deploy.operation.deploy.service.DServerService;
import com.rongda.deploy.operation.deploy.service.DeployService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Create By WeiBin on 2020/10/26 19:32
 *
 * @author WB
 */
@RestController
@RequestMapping("/upload")
@AllArgsConstructor
public class UploadController {

    private DAppService dAppService;

    private DeployService deployService;

    private DServerService dServerService;

    @RequestMapping("/upload")
    public R upload(@RequestParam(value = "file", required = false) MultipartFile file,
                    @RequestParam(value = "appId", required = true) Long appId) {
        if (file.isEmpty()) {
            return new R().error("上传失败，请选择文件");
        }
//        if (!file.getName().contains(".jar")) {
//            return new R().error("请上传正常格式的jar包");
//        }
        if (!this.uploadBefore(appId)) {
            return new R().error("服务器连接失败，请稍后重试");
        }
        App app = dAppService.queryById(appId);
        String filename = app.getStartScript();
        String filePath = app.getDeployPath();
        File dest = new File(filePath + "/" + filename);
        try {
            //TODO 这里修改成将文件上传到远程服务器而不是本地

            file.transferTo(dest);
            return new R<>().success("upload success");
        } catch (IOException e) {
            e.printStackTrace();
            return new R().error("upload failed");
        }
    }

    private boolean uploadBefore(Long id) {
        App app = dAppService.queryById(id);
        //执行备份脚本 暂时只能备份上一个版本的
        StringBuffer stringBuffer = new StringBuffer();
        String commend = stringBuffer.append("cd ").
                append(app.getBackupPath()).
                append("\n").
                append("./cope.sh ").
                append(app.getStartScript()).toString();
        String executeCommend = deployService.executeCommend(commend, this.dServerService.queryById(app.getServerId()));
        if ("connect fail".equals(executeCommend)) {
            return false;
        }
        return true;
    }
}
